//
//  TWBriefViewController.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/4/13.
//  Copyright © 2017年 个人. All rights reserved.
//  作者信息


// MARK:- 使用群组方式，将头部放最上面设置 表头为标题栏 

import UIKit
import SVProgressHUD

class TWBriefViewController: UIViewController {
    
    fileprivate lazy var titleLabel : UILabel = UILabel()
    fileprivate lazy var titleView : TWTitleView = TWTitleView()
    fileprivate lazy var authorHeaderView : TWAuthorHeaderView = TWAuthorHeaderView.createAuthorHeaderView()
    fileprivate lazy var tableView : UITableView = UITableView()
    fileprivate lazy var footerNullView : UILabel = UILabel()
    fileprivate lazy var shareViewAnimator : TWShareViewAnimator = TWShareViewAnimator()
    
    // MARK:- 属性
    fileprivate var dataArray = NSMutableArray()
    var pgcInfoModel : TWPgcInfoModel?
    var titleArray : [TWDiscoverTitleModel] = [TWDiscoverTitleModel]()
    var model : TWVideoCollectionOfAuthorWithCoverModel?{
        didSet {
            guard let _ = model else {
                return
            }
            loadTitleData()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 在页面出现的时候就将黑线隐藏起来
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        navigationController?.navigationBar.shadowImage = UIImage()
        navigationController?.navigationBar.backgroundColor = UIColor.white.withAlphaComponent(0.9)
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 在页面消失的时候就让navigationbar还原样式
        navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
        navigationController?.navigationBar.shadowImage = nil
        SVProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        SVProgressHUD.show()
        setupNav()
        self.setupTabelView()
        self.setupStateBarBackground()
    }
}

// MARK:- 请求数据
extension TWBriefViewController {
    fileprivate func loadTitleData(){
        titleArray.removeAll()
        let tempId = model?.header?.id
        guard let tempId1 = tempId else {
            return
        }
        let urlSrting = "https://baobab.kaiyanapp.com/api/v4/pgcs/detail/tab?_s=7a91ab5ad677a7b5e5237330d98b5a03&f=iphone&id=\(tempId1)&net=wifi&p_product=EYEPETIZER_IOS&u=27e73f129dc6a90ed0b2da2cb1c8b3d14829761d&v=3.4.2&vc=2611"
        TWNetworkTool.shareInstance.loadAuthorTitleViewData(urlString: urlSrting) { (result, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "加载失败")
                return
            }
            guard let result = result else {
                return
            }
            // pgcInfo转模型
            let pgcInfoDict = result["pgcInfo"] as! [String : AnyObject]
            self.pgcInfoModel = TWPgcInfoModel(dict: pgcInfoDict)
            self.authorHeaderView.model = self.pgcInfoModel
            // tabInfo -> tabList转模型
            let tabInfoDicts = result["tabInfo"]?["tabList"] as! [[String : AnyObject]]
            for item in tabInfoDicts {
                let titleModel = TWDiscoverTitleModel(dict: item)
                self.titleArray.append(titleModel)
            }
            self.setupTitleView()
            self.setupNullFooterView()
            self.TitleViewTitleButtonDidClick(index: 0)
        }
    }
    /// 请求最新网络数据
    fileprivate func loadNewRootData(urlString : String){
        TWNetworkTool.shareInstance.loadDiscoverViewData(urlString: urlString) { (result, error) in
            if error != nil {
                SVProgressHUD.showError(withStatus: "加载失败！")
            }
            guard let result = result else {
                return
            }
            // 处理cell相关的数据
            self.dealWithData(result: result)
        }
    }
    private func dealWithData(result : [String : AnyObject]){
        // 需要展示主体数据的数组
        let itemListArray = result["itemList"] as! [[String : AnyObject]]
        let tempArray : NSMutableArray = NSMutableArray()
        // 遍历数组,判断是什么类型，转成模型
        for item in itemListArray {
            let dataType = item["type"] as! String
            // dataType一共有14种类型,根据类型不同分别转成不同的模型
            switch dataType {
            case video:
                let itemModel : TWItemModel = TWItemModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([video : itemModel])
            case textFooter:
                let itemModel : TWTextFooterModel = TWTextFooterModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([textFooter : itemModel])
            case textHeader:
                let itemModel : TWTextHeaderModel = TWTextHeaderModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([textHeader : itemModel])
            case videoCollectionWithCover:
                let itemModel : TWItemCollectionModel = TWItemCollectionModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([videoCollectionWithCover : itemModel])
            case videoCollectionOfFollow:
                let itemModel : TWVideoCollectionOfFollowModel = TWVideoCollectionOfFollowModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([videoCollectionOfFollow : itemModel])
            case squareCardCollection:
                let itemModel : TWSquareCardCollectionModel = TWSquareCardCollectionModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([squareCardCollection : itemModel])
            case videoCollectionOfAuthorWithCover:
                let itemModel : TWVideoCollectionOfAuthorWithCoverModel = TWVideoCollectionOfAuthorWithCoverModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([videoCollectionOfAuthorWithCover : itemModel])
            case banner:
                let itemModel : TWBannerModel = TWBannerModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([banner : itemModel])
            case horizontalScrollCard:
                let itemModel : TWHorizontalScrollCard = TWHorizontalScrollCard(dict: item["data"] as! [String : AnyObject])
                tempArray.add([horizontalScrollCard : itemModel])
            case VideoCollectionWithBrief:
                let itemModel : TWVideoCollectionOfAuthorWithCoverModel = TWVideoCollectionOfAuthorWithCoverModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([VideoCollectionWithBrief : itemModel])
            case VideoCollectionOfHorizontalScrollCard :
                let itemModel : TWVideoCollectionOfHorizontalScrollCardModel = TWVideoCollectionOfHorizontalScrollCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([VideoCollectionOfHorizontalScrollCard : itemModel])
            case TextCard :
                let itemModel : TWTextCardModel = TWTextCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([TextCard : itemModel])
            case BriefCard :
                let itemModel : TWBriefCardModel = TWBriefCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([BriefCard : itemModel])
            case BlankCard :
                let itemModel : TWBlankCardModel = TWBlankCardModel(dict: item["data"] as! [String : AnyObject])
                tempArray.add([BlankCard : itemModel])
            default:
                TWLog(message: "这是一组未知类型的数据")
            }
        }
        dataArray.removeAllObjects()
        for item in tempArray {
            dataArray.add(item)
        }
        self.tableView.reloadData()
        self.tableView.setContentOffset(CGPoint(x: 0, y: -(NavigationBarHeight + AuthorHeaderViewHeight)), animated: true)
        SVProgressHUD.dismiss()
    } 
}

// MARK:- UI界面
extension TWBriefViewController {
    fileprivate func setupStateBarBackground(){
        let barBackgroundView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: BatteryHeight))
        barBackgroundView.backgroundColor = UIColor.white.withAlphaComponent(0.9)
        view.addSubview(barBackgroundView)
    }
    fileprivate func setupNav(){
        // 设置右边的分享按钮
        let rightButton = UIButton(type: .custom)
        rightButton.setImage(UIImage(named: "nav_share_44x44_"), for: .normal)
        rightButton.addTarget(self, action: #selector(rightShareBarButtonItemDidClick), for: .touchUpInside)
        rightButton.sizeToFit()
        // 往导航栏右边添加一个间隙
        let rightItem = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        rightItem.width = -15
        navigationItem.rightBarButtonItems = [rightItem,UIBarButtonItem(customView: rightButton)]

        // 设置中间的标题栏
        titleLabel.text = model?.header?.title
        titleLabel.font = UIFont(name: "FZLTZCHJW--GB1-0", size: 16)
        titleLabel.textColor = UIColor.black
        titleLabel.sizeToFit()
        navigationItem.titleView = titleLabel
        titleLabel.isHidden = true
    }
    fileprivate func setupTabelView(){
        automaticallyAdjustsScrollViewInsets = false
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: TWScreenWidth, height: TWScreenHeight), style: .plain)
        tableView.separatorStyle = .none
        tableView.backgroundColor = UIColor.white
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.contentInset = UIEdgeInsets(top: AuthorHeaderViewHeight + NavigationBarHeight, left: 0, bottom: 0, right: 0)
        tableView.separatorStyle = .none
        view.addSubview(tableView)
        tableView.register(UINib(nibName: "TWBannerCell", bundle: nil), forCellReuseIdentifier: BannerCell)
        tableView.register(UINib(nibName: "TWFooterCell", bundle: nil), forCellReuseIdentifier: FooterCell)
        tableView.register(UINib(nibName: "TWHeaderCell", bundle: nil), forCellReuseIdentifier: HeaderCell)
        tableView.register(UINib(nibName: "TWTextCardCell", bundle: nil), forCellReuseIdentifier: TextCardCell)
        tableView.register(UINib(nibName: "TWBriefCardCell", bundle: nil), forCellReuseIdentifier: BriefCardCell)
        tableView.register(UINib(nibName: "TWBlankCardCell", bundle: nil), forCellReuseIdentifier: BlankCardCell)
        tableView.register(UINib(nibName: "TWChoicenessItemCell", bundle: nil), forCellReuseIdentifier: VideoCell)
        tableView.register(UINib(nibName: "TWItemCollectionCell", bundle: nil), forCellReuseIdentifier: ItemCollectionCell)
        tableView.register(UINib(nibName: "TWSquareCardCollectionCell", bundle: nil), forCellReuseIdentifier: SquareCardTableViewCell)
        tableView.register(UINib(nibName: "TWHorizontalScrollCardCell", bundle: nil), forCellReuseIdentifier: HorizontalScrollCardCell)
        tableView.register(UINib(nibName: "TWVideoCollectionWithBrief", bundle: nil), forCellReuseIdentifier: VideoCollectionWithBrief)
        tableView.register(UINib(nibName: "TWVideoCollectionOfFollowCell", bundle: nil), forCellReuseIdentifier: VideoCollectionOfFollowCell)
        tableView.register(UINib(nibName: "TWVideoCollectionOfAuthorWithCoverCell", bundle: nil), forCellReuseIdentifier: VideoCollectionOfAuthorWithCoverCell)
        tableView.register(UINib(nibName: "TWVideoCollectionOfHorizontalScrollCardCell", bundle: nil), forCellReuseIdentifier: VideoCollectionOfHorizontalScrollCard)

        authorHeaderView.frame = CGRect(x: 0, y: -AuthorHeaderViewHeight, width: TWScreenWidth, height: AuthorHeaderViewHeight)
        authorHeaderView.model = pgcInfoModel
        tableView.addSubview(authorHeaderView)
    }
    fileprivate func setupTitleView(){
        titleView = TWTitleView(frame: CGRect(x: 0, y: 0, width: TWScreenWidth, height: DiscovertitleViewHeight))
        titleView.titleArray = self.titleArray
        titleView.delegate = self
    }
    fileprivate func setupNullFooterView(){
        // 没有数据时的tableFooterView
        footerNullView = UILabel(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100))
        footerNullView.text = "-end-"
        footerNullView.font = UIFont.init(name: "Lobster1.4", size: 15)
        footerNullView.textAlignment = .center
        tableView.tableFooterView = footerNullView
    }
}

// MARK:- 监听点击
extension TWBriefViewController {
    @objc fileprivate func rightShareBarButtonItemDidClick(){
        let shareVc : TWShareViewController = TWShareViewController()
        shareVc.modalPresentationStyle = .custom
        shareVc.transitioningDelegate = shareViewAnimator
        shareViewAnimator.presentedFrame = CGRect(x: 0, y: TWScreenHeight - 300, width: TWScreenWidth, height: 300)
        shareVc.model = model
        present(shareVc, animated: true, completion: nil)
    }
}
extension TWBriefViewController : UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 取出当前对应的类型
        let data = dataArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        // 根据类型展示cell
        switch key {
        case video:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCell, for: indexPath) as! TWChoicenessItemCell
            cell.selectionStyle = .none
            let itemModel = data.values.first as! TWItemModel
            cell.itemModel = itemModel
            return cell
        case textFooter:
            let cell = tableView.dequeueReusableCell(withIdentifier: FooterCell, for: indexPath) as! TWFooterCell
            cell.selectionStyle = .none
            let textFooter = data.values.first as! TWTextFooterModel
            cell.textFooter = textFooter
            return cell
        case textHeader:
            let cell = tableView.dequeueReusableCell(withIdentifier: HeaderCell, for: indexPath) as! TWHeaderCell
            cell.selectionStyle = .none
            let textHeader = data.values.first as! TWTextHeaderModel
            cell.textHeader = textHeader
            return cell
        case videoCollectionWithCover:
            let cell = tableView.dequeueReusableCell(withIdentifier: ItemCollectionCell, for: indexPath) as! TWItemCollectionCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWItemCollectionModel
            cell.itemCollectionModel = itemCollectionModel
            cell.detailCollectionView.fromWhichVc = FromRootVc
            return cell
        case videoCollectionOfFollow:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionOfFollowCell, for: indexPath) as! TWVideoCollectionOfFollowCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfFollowModel
            cell.videoCollectionOfFollowModel = itemCollectionModel
            cell.detailCollectionView.fromWhichVc = FromRootVc
            return cell
        case squareCardCollection:
            let cell = tableView.dequeueReusableCell(withIdentifier: SquareCardTableViewCell, for: indexPath) as! TWSquareCardCollectionCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWSquareCardCollectionModel
            cell.squareCardCollectionModel = itemCollectionModel
            return cell
        case videoCollectionOfAuthorWithCover:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionOfAuthorWithCoverCell, for: indexPath) as! TWVideoCollectionOfAuthorWithCoverCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfAuthorWithCoverModel
            cell.VideoCollectionOfAuthorWithCoverModel = itemCollectionModel
            cell.detailCollectionView.fromWhichVc = FromRootVc
            return cell
        case banner:
            let cell = tableView.dequeueReusableCell(withIdentifier: BannerCell, for: indexPath) as! TWBannerCell
            cell.selectionStyle = .none
            let bannerModel = data.values.first as! TWBannerModel
            cell.bannerModel = bannerModel
            return cell
        case horizontalScrollCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: HorizontalScrollCardCell, for: indexPath) as! TWHorizontalScrollCardCell
            cell.selectionStyle = .none
            let horizontalScrollCardCellModel = data.values.first as! TWHorizontalScrollCard
            cell.horizontalScrollCardModel = horizontalScrollCardCellModel
            cell.horizontalScrollCardCellDelegate = self as? HorizontalScrollCardCellDelegate
            return cell
        case VideoCollectionWithBrief:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionWithBrief, for: indexPath) as! TWVideoCollectionWithBrief
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfAuthorWithCoverModel
            cell.model = itemCollectionModel
            cell.bottomCollectionView.fromWhichVc = FromRootVc
            cell.videoCollectionWithBriefDelegate = self as? VideoCollectionWithBriefDelegate
            return cell
        case VideoCollectionOfHorizontalScrollCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: VideoCollectionOfHorizontalScrollCard, for: indexPath) as! TWVideoCollectionOfHorizontalScrollCardCell
            cell.selectionStyle = .none
            let itemCollectionModel = data.values.first as! TWVideoCollectionOfHorizontalScrollCardModel
            cell.model = itemCollectionModel
            cell.horizontalScrollCardCellDelegate = self as? VideoCollectionOfHorizontalScrollCardCellDelegate
            cell.bottomCollectionView.fromWhichVc = FromRootVc
            return cell
        case TextCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: TextCardCell, for: indexPath) as! TWTextCardCell
            cell.selectionStyle = .none
            let model = data.values.first as! TWTextCardModel
            cell.model = model
            return cell
        case BriefCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: BriefCardCell, for: indexPath) as! TWBriefCardCell
            cell.selectionStyle = .none
            let model = data.values.first as! TWBriefCardModel
            cell.model = model
            return cell
        case BlankCard:
            let cell = tableView.dequeueReusableCell(withIdentifier: BlankCardCell, for: indexPath) as! TWBlankCardCell
            cell.selectionStyle = .none
            return cell
        default:
            return UITableViewCell()
        }
    }
}

extension TWBriefViewController : UITableViewDelegate  {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return DiscovertitleViewHeight
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return titleView
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // 取出当前对应的类型
        let data = dataArray[indexPath.row] as! [String : AnyObject]
        let key = data.keys.first!
        switch key {
        case video:
            return VideoCellHeight
        case textFooter:
            return headerFooterCellHeight
        case textHeader:
            return headerFooterCellHeight
        case videoCollectionWithCover:
            return VideoCollectionCellHeight
        case videoCollectionOfFollow:
            return VideoCollectionCellHeight
        case squareCardCollection:
            return squareCardCellHeight
        case videoCollectionOfAuthorWithCover:
            return VideoCollectionCellHeight
        case banner:
            return VideoCellHeight
        case horizontalScrollCard:
            return VideoCellHeight
        case VideoCollectionWithBrief :
            return videoCollectionWithBriefCellHeight
        case VideoCollectionOfHorizontalScrollCard :
            return videoCollectionOfHorizontalScrollCardCellHeight
        case TextCard :
            return TextCardHeight
        case BriefCard :
            return BriefCardHeight
        case BlankCard :
            return BlankCardHeight
        default:
            return 0
        }
    }
}

// MARK:- titleView的代理方法
extension TWBriefViewController : titleViewDelegate{
    func TitleViewTitleButtonDidClick(index: Int) {
        loadNewRootData(urlString: (self.titleArray[index].apiUrl!))
    }
    func TitleViewPreviousClickTitleButton(index: Int) {
        print("第\(index)个按钮被重复点击")
    }
}

extension TWBriefViewController : UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = -(AuthorHeaderViewHeight + NavigationBarHeight)   // 初始是 -254
        if tableView.contentOffset.y >= offset {
            // 向上的时候改变 tableView的contentInset 来改变section的位子
            tableView.contentInset = UIEdgeInsets(top: -tableView.contentOffset.y, left: 0, bottom: 0, right: 0)
            if tableView.contentOffset.y >= -NavigationBarHeight {
                titleLabel.isHidden = false
                tableView.contentInset = UIEdgeInsets(top: NavigationBarHeight, left: 0, bottom: 0, right: 0)
            } else {
                titleLabel.isHidden = true
            }
        }
    }
}
